package com.zy.baselib.widget.input

import android.text.InputFilter
import android.text.Spanned
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * @author: shalei
 * @since: 2020-01-14 08:55
 * @Desc: 限制输入，汉字和空格不能输入
 **/
class InputFilterEnglish: InputFilter {


    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence {
        if(source == null || " " == source) {
            return ""
        }
        if(stringFilterChinese(source)) {
            return ""
        }
        return source
    }

    /**
     * 限制只能输入汉字，过滤非汉字
     * @param str 输入值
     * @return true 汉字；false 非汉字
     */
    private fun stringFilterChinese(str: CharSequence): Boolean { //只允许汉字，正则表达式匹配出所有非汉字
        val regEx = "[^\u4E00-\u9FA5]"
        val p: Pattern = Pattern.compile(regEx)
        val m: Matcher = p.matcher(str)
        return !m.find()
    }
}